package com.yanqu.road.server.manager.tomb;

import com.google.protobuf.AbstractMessage;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.logic.activity.tomb.config.TombConfig;
import com.yanqu.road.logic.activity.tomb.config.entity.ActivityTombEvent;
import com.yanqu.road.logic.activity.tomb.config.entity.ActivityTombRank;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.pb.tomb.Tomb;
import com.yanqu.road.server.CrossBaseServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.manager.config.GoodsMgr;
import com.yanqu.road.server.manager.tomb.business.TombCrossBusiness;
import com.yanqu.road.server.manager.tomb.entity.*;
import com.yanqu.road.server.manager.tomb.service.*;
import com.yanqu.road.server.manager.union.activitygroup.Cross2UnionActivityGroupMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.sync.message.Service;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;


public class TombServiceMgr extends TempMgr {

    private static Logger logger = LogManager.getLogger(TombServiceMgr.class.getName());
    private static final Map<Integer, TombActivity> activityMap = new ConcurrentHashMap<>();

    private static AtomicBoolean isLoading = new AtomicBoolean();

    public static TombActivity getActivity(int activityId) {
        if(!activityMap.containsKey(activityId)){
            initActivity(activityId);
        }
        return activityMap.get(activityId);
    }

    private static void initActivity(int activityId) {
        if(Cross2UnionActivityGroupMgr.getGroupMap(activityId) == null){
            logger.info("tomb活动 {} 初始，等待分组数据", activityId);
            return;
        }
        synchronized (activityMap){
            if(!activityMap.containsKey(activityId)){
                ActivityInfo activityInfo = ActivityBussiness.getActivityInfoByActivityId(activityId);
                TombActivity activity = new TombActivity(activityInfo);
                activity.loadConfig();
                activity.loadData();
                activityMap.put(activityId, activity);
            }
        }
    }

    public static void initService(Service syncMessageService) {
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_ENTER_MAZE, new TombInfoServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_DISPLAY_FIELD, new TombDisplayFieldServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_DISPLAY_ALLY_FIELD, new TombDisplayAllyFieldServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_MOVE, new TombMoveServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_DIG, new TombDigServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_EVENT_INFO, new TombEventInfoServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_EVENT_TOUCH, new TombEventTouchServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_CONFIG_INFO, new TombConfigInfoServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_HEARTBEAT, new TombHeartbeatServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_USER_CLICK, new TombUserClickServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_REWARD_SCORE_LIST, new TombRewardScoreListCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_USER_DETAIL_INFO, new TombUserDetailInfoCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_UNION_HELP_LIST, new TombUnionHelpListServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_MAZE_ELITE_NPC_LIST, new TombMazeEliteNpcListServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_MAZE_ELITE_NPC_LOG_LIST, new TombMazeEliteNpcLogListServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_MAZE_ELITE_NPC_REWARD, new TombMazeEliteNpcRewardServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_USER_LOG_LIST, new TombUserLogListServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_PARTNER_LIST, new TombPartnerListServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_FASTEST_PLAYER_INFO, new TombFastestPlayerServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_MAZE_INFO, new TombMazeInfoServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_PARTNER_INFO, new TombPartnerInfoServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_UNION_IN_TRAP_HELP, new TombUnionInTrapHelpServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_UNION_IN_TRAP_SEND_HELP, new TombUnionInTrapSendHelpServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_CROSS_ADD_ITEM, new TombAddItemServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_ACTIVITY_RELOAD, new TombActivityReloadServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_BUFF_REFRESH_PARTNER, new TombBuffRefreshPartnerServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_EVENT_EXPLORE, new TombEventExploreServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_EVENT_TAKE_CARE, new TombEventTakeCareServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_RED_DOT, new TombRedDotServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_BREAK_LOCK, new TombBreakLockServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_TRAP_INFO_LIST, new TombTrapInfoListServiceCmd());

        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_REPAIR_PROCESS_SYNC, new TombGetRepairProcessCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_REPAIR, new TombRepairCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_REPAIR_RANK, new TombGetRepairRankCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_CROSS_ADD_DOLL, new TombAddUserDollCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_CHANGE_DOLL, new TombChangeUserDollCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_CROSS_UNLOCK_PAY_DOLL, new TombUnlockPayDollCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_ACTIVITY_INFO_TO_CROSS, new TombActivityInfoServiceCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_UPDATE_AUTO_SWITCH_TO_CROSS, new TombChangeSwitchCmd());
        syncMessageService.addCrossServiceCommand(CrossProtocol.C_TOMB_ONE_CLICK_JUMP,
                new TombOneClickJumpServiceCmd()); // 秦始皇陵一键跳转至活动已解锁的最深层
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }


    public static boolean loadActivity() {
        try {
            isLoading.set(true);
            long serverId = CrossBaseServer.getInstance().getServerId();
            logger.info("服务器id:{}, 初始化tomb活动", serverId);
            String dateTimeString = DateHelper.getCurrentDateTimeString();
            List<Integer> activityTypeList = new ArrayList<>();
            activityTypeList.add(eActivityType.Tomb.getValue());
            Map<Integer, ActivityInfo> activityInfoMap = ActivityBussiness.getOpenCrossRankActivityInfoMap(activityTypeList, dateTimeString);

            //活动过滤
            Set<Integer> activityIdSet = new HashSet<>();
            for (Map.Entry<Integer, Map<Integer, UnionActivityGroup>> entry : Cross2UnionActivityGroupMgr.getGroupMap().entrySet()) {
                for (Map.Entry<Integer, UnionActivityGroup> groupEntry : entry.getValue().entrySet()) {
                    if(activityInfoMap.containsKey(groupEntry.getValue().getActivityId()) && groupEntry.getValue().getCrossServerId() == serverId){
                        activityIdSet.add(entry.getKey());
                    }
                }
            }

            List<Integer> activityIdList = new ArrayList<>();
            for (ActivityInfo value : activityInfoMap.values()) {
                if(activityIdSet.contains(value.getActivityId()) || serverId == value.getCrossId()){
                    activityIdList.add(value.getActivityId());
                }
            }
            if (activityIdList.isEmpty()) {
                logger.error("服务器id:{}, 没有配置tomb活动", serverId);
                return true;
            }

            for (TombActivity tombActivity : activityMap.values()) {
                boolean expire = true;
                for (Integer activityId : activityIdList) {
                    if (tombActivity.getActivityInfo().getActivityId() == activityId) {
                        expire = false;
                        break;
                    }
                }
                if (expire) {
                    activityMap.remove(tombActivity.getActivityInfo().getActivityId());
                }
            }

            for (ActivityInfo value : activityInfoMap.values()) {
                if(!activityIdList.contains(value.getActivityId())){
                    continue;
                }
                if(Cross2UnionActivityGroupMgr.getGroupMap(value.getActivityId()) == null){
                    logger.info("tomb活动 {} 初始，等待分组数据", value.getActivityId());
                    continue;
                }
                if (activityMap.containsKey(value.getActivityId())) {
                    TombActivity tombActivity = activityMap.get(value.getActivityId());
                    tombActivity.loadConfig();
                } else {
                    TombActivity activity = new TombActivity(value);
                    activity.loadConfig();
                    activity.loadData();
                    activityMap.put(value.getActivityId(), activity);
                }
            }
        } finally {
            isLoading.set(false);
        }
        return true;
    }

    @Override
    public boolean reloadConfig() throws Exception {
        loadActivity();
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        for (TombActivity tombActivity : activityMap.values()) {

            for (Map.Entry<Integer, DbActivityTombInfo> tombInfoEntry : tombActivity.getDbData().getDbActivityTombInfoMap().entrySet()) {
                TombCrossBusiness.saveDbActivityTombInfo(tombInfoEntry.getValue());
            }

            for (DbTombUser dbTombUser : tombActivity.getDbData().getDbTombUserMap().values()) {
                TombCrossBusiness.saveDbTombUser(dbTombUser);
            }

            for (Map.Entry<Integer, Map<Long, DbTombServerData>> mapEntry : tombActivity.getDbData().getDbTombServerDataMap().entrySet()) {
                for (DbTombServerData dbTombServerData : mapEntry.getValue().values()) {
                    TombCrossBusiness.saveDbTombServerData(dbTombServerData);
                }
            }

            for (Map.Entry<Integer, Map<Integer, Map<String, DbTombPosition>>> entry : tombActivity.getDbData().getDbTombPositionMap().entrySet()) {
                for (Map.Entry<Integer, Map<String, DbTombPosition>> mapEntry : entry.getValue().entrySet()) {
                    for (Map.Entry<String, DbTombPosition> positionEntry : mapEntry.getValue().entrySet()) {
                        TombCrossBusiness.saveDbTombPosition(positionEntry.getValue());
                    }
                }
            }

            for (Map.Entry<Integer, Map<Integer, TombMaze>> entry : tombActivity.getTombMazeMap().entrySet()) {
                for (Map.Entry<Integer, TombMaze> mazeEntry : entry.getValue().entrySet()) {
                    TombMaze tombMaze = mazeEntry.getValue();
                    DbTombMaze dbTombMaze = tombMaze.getDbTombMaze();
                    TombCrossBusiness.saveDbTombMaze(dbTombMaze);
                }
            }

            for (DbTombUserPosition dbTombUserPosition : tombActivity.getDbData().getDbTombUserPositionMap().values()) {
                TombCrossBusiness.saveDbTombUserPosition(dbTombUserPosition);
            }
            List<DbTombLog> waitList = tombActivity.getTombLog().getWaitList();
            for (DbTombLog dbTombLog : waitList) {
                TombCrossBusiness.saveDbTombLog(dbTombLog);
            }

        }
        return true;
    }


    public static int isOpen(int activityId, int groupId) {
        if (isLoading.get()) {
            return GameErrorCode.E_ERROR_ACTIVITY_LOADING;
        }
        TombActivity activity = getActivity(activityId);
        if (activity == null) {
            return GameErrorCode.E_ACTIVITY_NOT_OPEN;
        }
        if (!activity.getInitialized(groupId)) {
            return GameErrorCode.E_ACTIVITY_NOT_READY;
        }
        return 0;
    }

    public static Tomb.TombConfigInfoResp.Builder configInfo(int activityId, int groupId, long userId) {

        Tomb.TombConfigInfoResp.Builder builder = Tomb.TombConfigInfoResp.newBuilder();
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);

        activity.getConfigInfo(builder);
        return builder;
    }

    public static Tomb.TombEnterMazeResp.Builder info(int activityId, int groupId, long userId, long serverId, Tomb.TombEnterMazeReq req) {
        Tomb.TombEnterMazeResp.Builder builder = Tomb.TombEnterMazeResp.newBuilder();
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        activity.enterMaze(userId, serverId, req, builder);
        return builder;
    }

    public static Tomb.TombDisplayFieldResp.Builder displayField(int activityId, int groupId, long userId, Tomb.TombDisplayFieldReq req) {
        Tomb.TombDisplayFieldResp.Builder builder = Tomb.TombDisplayFieldResp.newBuilder();

        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        if (dbTombUser == null) {
            builder.setRet(GameErrorCode.E_TOMB_ACTIVITY_RELOAD);
            return builder;
        }
        TombMaze tombMaze = activity.getTombMaze(groupId, dbTombUser.getFloor());
        for (Tomb.FieldTemp field : req.getFieldsList()) {
            Tomb.FieldTemp.Builder fieldTemp = tombMaze.getFieldTemp(dbTombUser, field.getTimestamp(), field.getStartPosition(), field.getEndPosition());
            fieldTemp.setZoneId(field.getZoneId());
            builder.addFields(fieldTemp);
        }
        return builder;
    }

    public static Tomb.TombDisplayAllyFieldResp.Builder displayAllyField(int activityId, int groupId, Tomb.TombDisplayAllyFieldReq req) {
        Tomb.TombDisplayAllyFieldResp.Builder builder = Tomb.TombDisplayAllyFieldResp.newBuilder();
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        return builder;
    }

    public static Tomb.TombMoveResp.Builder move(int activityId, long userId, Tomb.TombMoveReq req) {
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        Tomb.TombMoveResp.Builder builder = Tomb.TombMoveResp.newBuilder();
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);

        return builder;
    }

    public static Tomb.TombUserClickResp.Builder userClick(int activityId, long userId, Tomb.TombUserClickReq req) {
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        Tomb.TombUserClickResp.Builder builder = Tomb.TombUserClickResp.newBuilder();
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        activity.userClick(userId, req, builder);
        return builder;
    }


    public static Tomb.TombDigResp.Builder dig(int activityId, long userId, Tomb.TombDigReq req) {
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        Tomb.TombDigResp.Builder builder = Tomb.TombDigResp.newBuilder();
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        return builder;
    }

    public static Tomb.TombEventExploreResp.Builder eventExplore(int activityId, long userId, Tomb.TombEventExploreReq req) {
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        Tomb.TombEventExploreResp.Builder builder = Tomb.TombEventExploreResp.newBuilder();
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        activity.eventExplore(userId, req, builder);
        return builder;
    }


    public static Tomb.TombEventInfoResp.Builder eventInfo(int activityId, long userId, Tomb.TombEventInfoReq req) {
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        Tomb.TombEventInfoResp.Builder builder = Tomb.TombEventInfoResp.newBuilder();
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        activity.eventInfo(userId, req, builder);
        return builder;
    }

    public static Tomb.TombEventTouchResp.Builder eventTouch(int activityId, long userId, Tomb.TombEventTouchReq req) {
        Tomb.TombEventTouchResp.Builder builder = Tomb.TombEventTouchResp.newBuilder();
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        activity.eventTouch(userId, req, builder);
        return builder;
    }

    public static Tomb.TombHeartBeatResp.Builder heartbeat(int activityId, long userId, Tomb.TombHeartbeatReq req) {
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        Tomb.TombHeartBeatResp.Builder builder = Tomb.TombHeartBeatResp.newBuilder();
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        activity.heartbeat(userId, req, builder);
        return builder;
    }

    public static Tomb.TombRewardScoreListResp.Builder rewardScoreRanking(int activityId, long userId, Tomb.TombRewardScoreListReq req) {
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        Tomb.TombRewardScoreListResp.Builder builder = Tomb.TombRewardScoreListResp.newBuilder();
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        int count = 0;
        for (DbTombUser dbTombUser : activity.getSortDbTombUserList(groupId)) {
            if (dbTombUser.getRewardScore() == 0) {
                break;
            }
            if (count >= req.getNum()) {
                break;
            }
            Tomb.RewardScoreTemp.Builder temp = Tomb.RewardScoreTemp.newBuilder();
            temp.setUserId(dbTombUser.getUserId());
            temp.setNickname(dbTombUser.getUserInfo().getNickName());
            temp.setUnionName(dbTombUser.getUserInfo().getUnionName());
            temp.setFloor(dbTombUser.getFloor());
            temp.setRewardScore(dbTombUser.getRewardScore());
            builder.addList(temp);
            count++;
        }
        return builder;
    }

    public static Tomb.TombUserDetailInfoResp.Builder userDetailInfo(int activityId, long userId, Tomb.TombUserDetailInfoReq req) {
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        Tomb.TombUserDetailInfoResp.Builder builder = Tomb.TombUserDetailInfoResp.newBuilder();
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(req.getUserId());
        if (dbTombUser == null) {
            builder.setRet(GameErrorCode.E_TOMB_USER_NOT_FOUND);
            return builder;
        }
        builder.setInfo(dbTombUser.toPlayerBaseTempBuilder());
        return builder;
    }

    public static Tomb.TombUnionHelpListResp.Builder unionHelpList(int activityId, long userId) {
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        Tomb.TombUnionHelpListResp.Builder builder = Tomb.TombUnionHelpListResp.newBuilder();
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        if (dbTombUser == null) {
            builder.setRet(GameErrorCode.E_TOMB_USER_NOT_FOUND);
            return builder;
        }

        TombMaze tombMaze = activity.getTombMaze(groupId, dbTombUser.getFloor());
        List<Tomb.TombUnionHelpInfoTemp> tombUnionHelpList = tombMaze.getTombUnionHelpList(dbTombUser);
        builder.addAllList(tombUnionHelpList);


        return builder;
    }

    public static Tomb.TombUserLogListResp.Builder userLogList(int activityId, long userId, Tomb.TombUserLogListReq req) {
        Tomb.TombUserLogListResp.Builder builder = Tomb.TombUserLogListResp.newBuilder();
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        if (dbTombUser == null) {
            builder.setRet(GameErrorCode.E_TOMB_USER_NOT_FOUND);
            return builder;
        }
        if (req.getType() == 1) {
            List<DbTombLog> userList = activity.getTombLog().getUserList(dbTombUser.getUserId(), dbTombUser.getUserInfo().getUnionUid());
            for (DbTombLog dbTombLog : userList) {
                builder.addList(dbTombLog.toTempBuilder(activity));
            }
        } else {
            List<DbTombLog> dbTombLogs = activity.getTombLog().getList(String.valueOf(activityId), false);
            for (DbTombLog dbTombLog : dbTombLogs) {
                if(dbTombLog.getGroupId() != groupId){
                    continue;
                }
                builder.addList(dbTombLog.toTempBuilder(activity));
            }
        }


        return builder;
    }

    public static Tomb.TombMazeEliteNpcListResp.Builder mazeEliteNpcList(int activityId, long userId) {
        Tomb.TombMazeEliteNpcListResp.Builder builder = Tomb.TombMazeEliteNpcListResp.newBuilder();
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        if (dbTombUser == null) {
            builder.setRet(GameErrorCode.E_TOMB_USER_NOT_FOUND);
            return builder;
        }
        for (TombMaze tombMaze : activity.getTombMazeMap(groupId).values()) {
            if (tombMaze.getDbTombMaze().getEliteNpcEvent().length() == 0) {
                continue;
            }
            DbTombPosition dbTombPosition = tombMaze.getDbTombPosition(tombMaze.getDbTombMaze().getEliteNpcEvent());
            if (dbTombPosition == null) {
                continue;
            }

            ActivityTombEvent activityTombEvent = activity.getConfig().getEvent(dbTombPosition.getEventId());
            Tomb.TombMazeEliteNpcTemp.Builder temp = Tomb.TombMazeEliteNpcTemp.newBuilder();
            temp.setNpcId(activityTombEvent.getNpcId());
            temp.setFloor(tombMaze.getFloor());

            List<Tomb.TombMazeEliteNpcLogTemp> eliteNpcLogList = tombMaze.getEliteNpcLogList();
            boolean canRewardEliteEvent = tombMaze.canRewardEliteEvent(eliteNpcLogList, dbTombUser, dbTombPosition);
            temp.setCanReward(canRewardEliteEvent);
            builder.addList(temp);
        }
        return builder;
    }

    public static Tomb.TombMazeEliteNpcLogListResp.Builder mazeEliteNpcLogList(int activityId, long userId, Tomb.TombMazeEliteNpcLogListReq req) {
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        Tomb.TombMazeEliteNpcLogListResp.Builder builder = Tomb.TombMazeEliteNpcLogListResp.newBuilder();
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        if (dbTombUser == null) {
            builder.setRet(GameErrorCode.E_TOMB_USER_NOT_FOUND);
            return builder;
        }
        TombMaze tombMaze = activity.getTombMaze(groupId, req.getFloor());
        if (tombMaze == null) {
            builder.setRet(GameErrorCode.E_TOMB_MAZE_FLOOR_NOT_FOUND);
            return builder;
        }
        DbTombPosition dbTombPosition = tombMaze.getDbTombPosition(tombMaze.getDbTombMaze().getEliteNpcEvent());
        if (dbTombPosition == null) {
            builder.setRet(GameErrorCode.E_TOMB_MAZE_ELITE_NPC_NOT_FOUND);
            return builder;
        }
        builder.setHp(dbTombPosition.getCurrentHp());
        builder.setMaxHp(dbTombPosition.getMaxHp());
        if (dbTombPosition.getFinishUserId() > 0) {
            DbTombUser dbTombUser1 = activity.getDbData().getDbTombUser(dbTombPosition.finishUserId);
            builder.setFinishUser(dbTombUser1.toEventUserInfoBuilder());
        }
        builder.setCanReward(false);


        List<Tomb.TombMazeEliteNpcLogTemp> eliteNpcLogList = tombMaze.getEliteNpcLogList();
        builder.addAllList(eliteNpcLogList);

        if (dbTombPosition.isAlive()) {
            return builder;
        }

        if (!dbTombPosition.getEventInfoMap().containsKey(userId)) {
            return builder;
        }

        PositionInfo positionInfo = dbTombPosition.getEventInfoMap().get(userId);
        if (positionInfo.isReward()) {
            return builder;
        }
        boolean canRewardEliteEvent = tombMaze.canRewardEliteEvent(eliteNpcLogList, dbTombUser, dbTombPosition);
        builder.setCanReward(canRewardEliteEvent);
        return builder;
    }


    public static Tomb.TombMazeEliteNpcRewardResp.Builder mazeEliteNpcReward(int activityId, long userId, Tomb.TombMazeEliteNpcRewardReq req) {
        if (req.hasOneKey() && req.getOneKey()) {
            return mazeEliteNpcRewardOneKey(activityId, userId);
        } else {
            return mazeEliteNpcRewardNormal(activityId, userId, req);
        }
    }

    public static Tomb.TombMazeEliteNpcRewardResp.Builder mazeEliteNpcRewardNormal(int activityId, long userId, Tomb.TombMazeEliteNpcRewardReq req) {
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        Tomb.TombMazeEliteNpcRewardResp.Builder builder = Tomb.TombMazeEliteNpcRewardResp.newBuilder();
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        if (dbTombUser == null) {
            builder.setRet(GameErrorCode.E_TOMB_USER_NOT_FOUND);
            return builder;
        }
        TombMaze tombMaze = activity.getTombMaze(groupId, req.getFloor());
        if (tombMaze == null) {
            builder.setRet(GameErrorCode.E_TOMB_MAZE_FLOOR_NOT_FOUND);
            return builder;
        }
        DbTombPosition dbTombPosition = tombMaze.getDbTombPosition(tombMaze.getDbTombMaze().getEliteNpcEvent());
        if (dbTombPosition == null) {
            builder.setRet(GameErrorCode.E_TOMB_MAZE_ELITE_NPC_NOT_FOUND);
            return builder;
        }

        boolean containsKey = dbTombPosition.getEventInfoMap().containsKey(userId);
        if (!containsKey) {
            builder.setRet(GameErrorCode.E_TOMB_USER_NOT_FOUND);
            return builder;
        }
        int type = eGamePlayerEventType.TombEliteAttackRankReward.getValue();
        ActivityTombEvent activityTombEvent = activity.getConfig().getEvent(dbTombPosition.getEventId());
        if (activityTombEvent.getEventType() == 4) {
            type = eGamePlayerEventType.TombBossAttackRankReward.getValue();
        }

        ArrayList<PositionInfo> positionInfos = new ArrayList<>(dbTombPosition.getEventInfoMap().values());
        positionInfos.sort(Comparator.comparing(PositionInfo::getAttack).reversed());
        int rank = 1;
        PositionInfo positionInfo = null;
        for (PositionInfo _positionInfo : positionInfos) {
            if (_positionInfo.getUserId() == userId) {
                positionInfo = _positionInfo;
                break;
            }
            rank++;
        }

        if (positionInfo == null) {
            builder.setPersonalScore(dbTombUser.getScore());
            builder.setUnionScore(dbTombUser.getUnionScore());
            return builder;
        }

        if (positionInfo.isReward()) {
            builder.setPersonalScore(dbTombUser.getScore());
            builder.setUnionScore(dbTombUser.getUnionScore());
            return builder;
        }
        for (ActivityTombRank activityTombRank : activity.getConfig().getRanks()) {
            if (activityTombRank.getType() == type) {
                if (rank >= activityTombRank.getParams().get(0) && rank <= activityTombRank.getParams().get(1)) {
                    positionInfo.setReward(true);
                    builder.setRewards(PropertyHelper.parsePropertyToString(activityTombRank.getRewards()));
                    dbTombPosition.refreshUpdateTime();
                }
            }
        }
        Property property = tombMaze.addProperty(builder.getRewards(), dbTombUser);
        builder.setRewards(PropertyHelper.parsePropertyToString(property));

        dbTombUser.refreshUpdateTime();
        builder.setPersonalScore(dbTombUser.getScore());
        builder.setUnionScore(dbTombUser.getUnionScore());
        return builder;
    }

    public static Tomb.TombMazeEliteNpcRewardResp.Builder mazeEliteNpcRewardOneKey(int activityId, long userId) {
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        Tomb.TombMazeEliteNpcRewardResp.Builder builder = Tomb.TombMazeEliteNpcRewardResp.newBuilder();
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        if (dbTombUser == null) {
            builder.setRet(GameErrorCode.E_TOMB_USER_NOT_FOUND);
            return builder;
        }
        for (TombMaze tombMaze : activity.getTombMazeMap(groupId).values()) {
            if (tombMaze == null) {
                ret = GameErrorCode.E_TOMB_MAZE_FLOOR_NOT_FOUND;
                continue;
            }
            DbTombPosition dbTombPosition = tombMaze.getDbTombPosition(tombMaze.getDbTombMaze().getEliteNpcEvent());
            if (dbTombPosition == null) {
                ret = GameErrorCode.E_TOMB_MAZE_ELITE_NPC_NOT_FOUND;
                continue;
            }

            boolean containsKey = dbTombPosition.getEventInfoMap().containsKey(userId);
            if (!containsKey) {
                ret = GameErrorCode.E_TOMB_USER_NOT_FOUND;
                continue;
            }
            int type = eGamePlayerEventType.TombEliteAttackRankReward.getValue();
            ActivityTombEvent activityTombEvent = activity.getConfig().getEvent(dbTombPosition.getEventId());
            if (activityTombEvent.getEventType() == 4) {
                type = eGamePlayerEventType.TombBossAttackRankReward.getValue();
            }

            ArrayList<PositionInfo> positionInfos = new ArrayList<>(dbTombPosition.getEventInfoMap().values());
            positionInfos.sort(Comparator.comparing(PositionInfo::getAttack).reversed());
            int rank = 1;
            PositionInfo positionInfo = null;
            for (PositionInfo _positionInfo : positionInfos) {
                if (_positionInfo.getUserId() == userId) {
                    positionInfo = _positionInfo;
                    break;
                }
                rank++;
            }

            if (positionInfo == null) {
                continue;
            }

            if (positionInfo.isReward()) {
                continue;
            }
            Property totalReward = new Property();
            for (ActivityTombRank activityTombRank : activity.getConfig().getRanks()) {
                if (activityTombRank.getType() == type) {
                    if (rank >= activityTombRank.getParams().get(0) && rank <= activityTombRank.getParams().get(1)) {
                        positionInfo.setReward(true);
                        Tomb.TombMazeEliteNpcRewardOneKey.Builder builderOneKey = Tomb.TombMazeEliteNpcRewardOneKey.newBuilder();
                        Property addReward = activityTombRank.getRewards();
                        totalReward.addProperty(addReward);
                        builderOneKey.setRewards(PropertyHelper.parsePropertyToString(addReward));
                        builderOneKey.setFloor(dbTombPosition.getFloor());
                        builderOneKey.setRank(rank);
                        builder.addOneKeyRewards(builderOneKey);
                        dbTombPosition.refreshUpdateTime();
                    }
                }
            }
            // 添加道具
            tombMaze.addProperty(totalReward, dbTombUser);
        }

        builder.setRet(0);
        if (builder.getOneKeyRewardsList().isEmpty()) {
            builder.setRet(ret);
        }
        dbTombUser.refreshUpdateTime();
        builder.setOneKey(true);
        builder.setPersonalScore(dbTombUser.getScore());
        builder.setUnionScore(dbTombUser.getUnionScore());
        return builder;
    }

    public static Tomb.TombRepairInfoSync.Builder getRepairProcessInfo(int activityId, long userId, long serverId, String unionUid) {
        Tomb.TombRepairInfoSync.Builder builder = Tomb.TombRepairInfoSync.newBuilder();
        if (isLoading.get()) {
            builder.setRet(GameErrorCode.E_ERROR_ACTIVITY_LOADING);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        if (dbTombUser == null) {
            builder.setRet(GameErrorCode.E_UNION_ACTIVITY_GROUP_NO_ABLE);
            //builder.setRet(GameErrorCode.E_TOMB_USER_NOT_FOUND);
            return builder;
        }
        if (StringUtils.isNullOrEmpty(unionUid)) {
            builder.setRet(GameErrorCode.E_TOMB_ACTIVITY_NOT_JOIN_UNION);
            return builder;
        }
        TombActivityUnion tombActivityUnion = getActivity(activityId).getActivityUnion(unionUid);
        if (tombActivityUnion == null) {
            builder.setRet(GameErrorCode.E_ERROR_DATA);
            return builder;
        }
        long unionTotalProgress = tombActivityUnion.getUnionTotalProgress();
        tombActivityUnion.updateProgressMap(unionTotalProgress);
        builder.addAllRepairData(tombActivityUnion.getProgressProto());
        return builder;

    }


    public static Tomb.TombRepairResp.Builder tombRepair(int oneKey, long useItemNum, long userId, int activityId, String unionUid) {
        Tomb.TombRepairResp.Builder builder = Tomb.TombRepairResp.newBuilder();

        if (isLoading.get()) {
            builder.setRet(GameErrorCode.E_ERROR_ACTIVITY_LOADING);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);

        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        if (dbTombUser == null) {
            builder.setRet(GameErrorCode.E_TOMB_USER_NOT_FOUND);
            return builder;
        }
        if (StringUtils.isNullOrEmpty(unionUid)) {
            builder.setRet(GameErrorCode.E_TOMB_ACTIVITY_NOT_JOIN_UNION);
            return builder;
        }
        TombActivityUnion tombActivityUnion = getActivity(activityId).getActivityUnion(unionUid);
        if (tombActivityUnion == null) {
            builder.setRet(GameErrorCode.E_ERROR_DATA);
            return builder;
        }
        Tomb.TombRepairResp.Builder respBuilder = tombActivityUnion.tombRepair(userId, useItemNum);
        return respBuilder;
    }

    public static Tomb.TombRepairRankResp.Builder getRepairRank(int activityId, long userId) {
        Tomb.TombRepairRankResp.Builder builder = Tomb.TombRepairRankResp.newBuilder();

        if (isLoading.get()) {
            builder.setRet(GameErrorCode.E_ERROR_ACTIVITY_LOADING);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);

        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        if (dbTombUser == null) {
            builder.setRet(GameErrorCode.E_TOMB_USER_NOT_FOUND);
            return builder;
        }
        if (StringUtils.isNullOrEmpty(dbTombUser.getUserInfo().getUnionUid())) {
            return builder;
        }
        TombActivityUnion tombActivityUnion = getActivity(activityId).getActivityUnion(dbTombUser.getUserInfo().getUnionUid());
        if (tombActivityUnion == null) {
            return builder;
        }
        builder = tombActivityUnion.getNiantuRank(userId);
        return builder;

    }

    public static Tomb.TombPartnerListResp.Builder partnerList(int activityId, long userId) {
        Tomb.TombPartnerListResp.Builder builder = Tomb.TombPartnerListResp.newBuilder();
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        if (dbTombUser == null) {
            builder.setRet(GameErrorCode.E_TOMB_USER_NOT_FOUND);
            return builder;
        }
        for (PartnerInfo partnerInfo : dbTombUser.getPartnerInfoMap().values()) {
            PartnerUpgradeInfo partnerUpgradeInfo = dbTombUser.acquirePartnerUpgradeInfo(partnerInfo.getId());
            Tomb.PartnerTemp.Builder p = Tomb.PartnerTemp.newBuilder();
            p.setId(partnerInfo.getId());
            p.setBaseEarn(partnerInfo.getAbility());
            p.setEarn(partnerUpgradeInfo.getResultAbility(partnerInfo.getAbility()));
            p.setUpgradeTimes(partnerUpgradeInfo.getTimes());
            p.setPercentage(partnerUpgradeInfo.getPercentage());
            p.setFixedValue(partnerUpgradeInfo.getFixedValue());
            builder.addList(p);
        }
        return builder;
    }

    public static Tomb.TombFastestPlayerResp.Builder fastestPlayer(int activityId, long userId) {
        Tomb.TombFastestPlayerResp.Builder builder = Tomb.TombFastestPlayerResp.newBuilder();
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        activity.fastestPlayer(userId, builder);
        return builder;
    }

    public static Tomb.TombMazeInfoResp.Builder mazeInfo(int activityId, long userId) {
        Tomb.TombMazeInfoResp.Builder builder = Tomb.TombMazeInfoResp.newBuilder();
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        activity.mazeInfo(userId, builder);
        return builder;
    }

    public static Tomb.TombPartnerInfoResp.Builder partnerInfo(int activityId, long userId) {
        Tomb.TombPartnerInfoResp.Builder builder = Tomb.TombPartnerInfoResp.newBuilder();
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        activity.partnerInfo(userId, builder);
        return builder;
    }

    public static Tomb.TombUnionInTrapHelpResp.Builder unionInTrapHelp(int activityId, long userId, Tomb.TombUnionInTrapHelpReq req) {
        Tomb.TombUnionInTrapHelpResp.Builder builder = Tomb.TombUnionInTrapHelpResp.newBuilder();
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        activity.unionInTrapHelp(userId, req, builder);

        return builder;
    }


    public static Tomb.TombUnionInTrapSendHelpResp.Builder unionInTrapSendHelp(int activityId, long userId, Tomb.TombUnionInTrapSendHelpReq req) {
        Tomb.TombUnionInTrapSendHelpResp.Builder builder = Tomb.TombUnionInTrapSendHelpResp.newBuilder();
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        activity.unionInTrapSendHelp(userId, req, builder);
        return builder;
    }


    public static Tomb.TombCrossUserAddItemResp.Builder addItem(int activityId, long userId, long serverId, Tomb.TombCrossUserAddItemReq req) {
        Tomb.TombCrossUserAddItemResp.Builder builder = Tomb.TombCrossUserAddItemResp.newBuilder();
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        dbTombUser.addEnergy(req.getAddEnergy());
        builder.setEnergy(dbTombUser.getEnergy(activity.getConfig().getConfig()));
        return builder;
    }

    public synchronized static Tomb.TombActivityReloadResp.Builder activityReload(int activityId) {
        Tomb.TombActivityReloadResp.Builder builder = Tomb.TombActivityReloadResp.newBuilder();
        if (isLoading.get()) {
            return builder;
        }
        boolean b = activityMap.containsKey(activityId);
        if (b) {
            //如果活动已存在，则直接重新加载配置
            TombActivity tombActivity = activityMap.get(activityId);
            tombActivity.loadConfig();
            return builder;
        }
        loadActivity();
        return builder;
    }

    public static CompletableFuture<AbstractMessage.Builder<?>> buffRefreshPartner(int activityId, long userId, Tomb.TombBuffRefreshPartnerReq req, CompletableFuture<AbstractMessage.Builder<?>> completableFuture) {
        Tomb.TombBuffRefreshPartnerResp.Builder builder = Tomb.TombBuffRefreshPartnerResp.newBuilder();
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);

        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            completableFuture.complete(builder);
            return completableFuture;
        }
        TombActivity activity = activityMap.get(activityId);

        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        if (dbTombUser == null) {
            builder.setRet(GameErrorCode.E_ERROR_DATA);
            completableFuture.complete(builder);
            return completableFuture;
        }
        activity.buffRefreshPartner(dbTombUser, req, builder, completableFuture);
        return completableFuture;
    }

    public static Map<Integer, TombActivity> getActivityMap() {
        return activityMap;
    }

    public static Tomb.TombChangeDollRespMsg.Builder changeUserDoll(int activityId, long userId, int dollId) {
        Tomb.TombChangeDollRespMsg.Builder builder = Tomb.TombChangeDollRespMsg.newBuilder();
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        Map<Integer, Long> dollMap = dbTombUser.getDollMap();
        if (!dollMap.containsKey(dollId)) {
            builder.setRet(GameErrorCode.E_TOMB_DOLL_NO_FOUND);
            return builder;
        }
        if (dollMap.get(dollId).equals(0L) && activity.getConfig().getConfig().getTOMB_ALL_DOLL_ID_LIST().get(0) != dollId) {
            builder.setRet(GameErrorCode.E_TOMB_DOLL_NO_HAVE);
            return builder;
        } else if (System.currentTimeMillis() >= dollMap.get(dollId) && activity.getConfig().getConfig().getTOMB_ALL_DOLL_ID_LIST().get(0) != dollId) {
            builder.setRet(GameErrorCode.E_TOMB_DOLL_OVER_TIME);
            return builder;
        }
        dbTombUser.setDollId(dollId);
        builder.setRet(0);
        return builder;
    }

    public static Tomb.TombUnlockPayDollResp.Builder unlockPayDoll(int activityId, long userId, int dollId, long value) {
        Tomb.TombAddDollResp.Builder addBuilder = addUserDoll(activityId, userId, dollId, 1);
        Tomb.TombUnlockPayDollResp.Builder builder = Tomb.TombUnlockPayDollResp.newBuilder();
        builder.setRet(addBuilder.getRet());
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        int scoreItemId = activity.getConfig().getConfig().getTOMB_SCORE_ITEM_ID();
        int count = activity.getConfig().getConfig().getTOMB_FAST_FUNCTION_OPEN_CONDITION().getCountByGoodsId(scoreItemId).intValue();
        if (count > 0) {
            if (dbTombUser.getScore() < count) {
                builder.setRet(GameErrorCode.E_TOMB_NOT_ENOUGH_SCORE);
                return builder;
            }
        }
        for (Map.Entry<Integer, Long> entry : dbTombUser.getDollMap().entrySet()) {
            Tomb.TombDollInfo.Builder dollInfoBuilder = Tomb.TombDollInfo.newBuilder();
            dollInfoBuilder.setDollId(entry.getKey());
            dollInfoBuilder.setExpireTime(entry.getValue());
            builder.addDollInfo(dollInfoBuilder);
        }
        return builder;


    }

    public static Tomb.TombAddDollResp.Builder addUserDoll(int activityId, long userId, int dollId, long value) {
        Tomb.TombAddDollResp.Builder builder = Tomb.TombAddDollResp.newBuilder();
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        Map<Integer, Long> dollMap = dbTombUser.getDollMap();

        long addTime;
        boolean first = false;
        try {
            addTime = 1000L * GoodsMgr.getGoodsInfo(dollId).getParamList().get(0).intValue() * value;
        } catch (Exception e) {
            getLogger().error("TombMgr error on addDoll! GoodsInfo is null!");
            builder.setRet(-1);
            return builder;
        }
        TombConfig config = activity.getConfig();
        if (!config.getConfig().getTOMB_ALL_DOLL_ID_LIST().contains(dollId)) {
            builder.setRet(-1);
            return builder;
        }
        if (!dollMap.containsKey(dollId)) {
            dollMap.put(dollId, 0L);
        }
        long now = System.currentTimeMillis();
        if (dollMap.get(dollId) < now) {
            dollMap.put(dollId, now + addTime);
            first = true;
        } else {
            dollMap.put(dollId, dollMap.get(dollId) + addTime);
        }
        dbTombUser.refreshUpdateTime();
        int takeCareDollId = config.getConfig().getTOMB_ALL_DOLL_ID_LIST().get(1);
        if (dollId == takeCareDollId && first) {
            List<Integer> autoList = new ArrayList<>(config.getAutoSwitch());
            activity.updateUserSwitch(userId, autoList);
        }
        builder.setRet(0);
        return builder;
    }


    /**
     * 判断是否可以打理
     */
    public static boolean canTakeCare(int activityId, DbTombUser dbTombUser) {
        TombActivity activity = activityMap.get(activityId);
        Map<Integer, Long> dollMap = dbTombUser.getDollMap();
        int takeCareDollId = activity.getConfig().getConfig().getTOMB_ALL_DOLL_ID_LIST().get(1);
        return dollMap.get(takeCareDollId) >= System.currentTimeMillis();

    }

    /**
     * 更新玩偶是否过期
     */
    public static void checkDollOverTime(int activityId, DbTombUser dbTombUser) {
        TombActivity activity = activityMap.get(activityId);
        int originalDollId = activity.getConfig().getConfig().getTOMB_ALL_DOLL_ID_LIST().get(0);
        if (dbTombUser.getDollId() == originalDollId) {
            return;
        }
        long useDollLimitTime = dbTombUser.getDollMap().get(dbTombUser.getDollId());
        if (useDollLimitTime == 0) {
            dbTombUser.setDollId(originalDollId);
            dbTombUser.refreshUpdateTime();
            return;
        } else if (useDollLimitTime < System.currentTimeMillis()) {
            dbTombUser.setDollId(originalDollId);
            dbTombUser.refreshUpdateTime();
            return;
        }
    }

    public static Tomb.TombEventExploreResp.Builder eventTakeCare(int activityId, long userId, Tomb.TombEventTakeCareReq req) {
        Tomb.TombEventExploreResp.Builder builder = Tomb.TombEventExploreResp.newBuilder();
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        activity.eventTakeCare(userId, req, builder);
        return builder;
    }

    public static Tomb.TombActivityInfoResp.Builder updateDbUserInfo(int activityId, long userId, long serverId, Tomb.TombActivityInfoToCrossReq req) {
        Tomb.TombActivityInfoResp.Builder builder = Tomb.TombActivityInfoResp.newBuilder();   //无所谓的返回
        TombActivity activity = activityMap.get(activityId);
        if (activity == null) {
            return builder;
        }
        activity.updateDbUser(userId, serverId, req, builder);
        return builder;
    }

    public static Tomb.TombUpdateAutoEventSwitchRespMsg.Builder updateTakeCareSwitch(int activityId, long userId, List<Integer> switchList) {
        Tomb.TombUpdateAutoEventSwitchRespMsg.Builder builder = Tomb.TombUpdateAutoEventSwitchRespMsg.newBuilder();
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        builder.setRet(activity.updateUserSwitch(userId, switchList));
        return builder;

    }

    public static Tomb.TombRedDotResp.Builder redDot(int activityId, int groupId, long userId, Tomb.TombRedDotReq req) {
        Tomb.TombRedDotResp.Builder builder = Tomb.TombRedDotResp.newBuilder();
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        if (dbTombUser == null) {
            return builder;
        }
        TombMaze tombMaze = activity.getTombMaze(groupId, dbTombUser.getFloor());
        if(tombMaze == null){
            return builder;
        }
        List<Tomb.TombUnionHelpInfoTemp> tombUnionHelpList = tombMaze.getTombUnionHelpList(dbTombUser);
        for (Tomb.TombUnionHelpInfoTemp tombUnionHelpInfoTemp : tombUnionHelpList) {
            if (tombUnionHelpInfoTemp.getTimestamp() > req.getTimestamp()) {
                builder.setUnionHelp(true);
                break;
            }
        }
        if (dbTombUser.getEnergy() >= activity.getConfig().getConfig().getTOMB_ENERGY_LIMIT()) {
            builder.setFullEnergy(true);
        }

        for (TombMaze _tombMaze : activity.getTombMazeMap(groupId).values()) {
            if (_tombMaze.getDbTombMaze().getEliteNpcEvent().length() == 0) {
                continue;
            }
            DbTombPosition dbTombPosition = _tombMaze.getDbTombPosition(_tombMaze.getDbTombMaze().getEliteNpcEvent());
            if (dbTombPosition == null) {
                continue;
            }
            ActivityTombEvent activityTombEvent = activity.getConfig().getEvent(dbTombPosition.getEventId());
            Tomb.TombMazeEliteNpcTemp.Builder temp = Tomb.TombMazeEliteNpcTemp.newBuilder();
            temp.setNpcId(activityTombEvent.getNpcId());
            temp.setFloor(_tombMaze.getFloor());

            List<Tomb.TombMazeEliteNpcLogTemp> eliteNpcLogList = _tombMaze.getEliteNpcLogList();
            boolean canRewardEliteEvent = _tombMaze.canRewardEliteEvent(eliteNpcLogList, dbTombUser, dbTombPosition);
            if (canRewardEliteEvent) {
                builder.setEliteReward(canRewardEliteEvent);
                break;
            }
        }

        return builder;
    }


    public static Tomb.TombBreakLockRespMsg.Builder breakLock(int activityId, int groupId, long userId, Tomb.TombBreakLockReq req) {
        Tomb.TombBreakLockRespMsg.Builder builder = Tomb.TombBreakLockRespMsg.newBuilder();
        builder.setRow(0);
        builder.setColumn(0);
        builder.setRet(0);
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            builder.setRet(ret);
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        DbTombUser dbTombUser = activity.getDbData().getDbTombUser(userId);
        if (dbTombUser == null) {
            builder.setRet(GameErrorCode.E_TOMB_USER_NOT_FOUND);
            return builder;
        }
        synchronized (dbTombUser.getPvpUnionChooseMap()) {
            if (!StringUtils.isNullOrEmpty(dbTombUser.getLockEvent())) {
                builder.setRet(GameErrorCode.E_TOMB_EVENT_NOT_HANDLE);
                return builder;
            }
            TombMaze tombMaze = activity.getTombMaze(groupId, dbTombUser.getFloor());
            tombMaze.userBreakLock(dbTombUser, builder);
        }
        return builder;
    }

    public static Tomb.TombTrapInfoRespMsg.Builder trapInfoList(int activityId, int groupId, Tomb.TombTrapInfoReqMsg req) {
        Tomb.TombTrapInfoRespMsg.Builder builder = Tomb.TombTrapInfoRespMsg.newBuilder();
        int ret = isOpen(activityId, groupId);
        if (ret > 0) {
            return builder;
        }
        TombActivity activity = activityMap.get(activityId);
        activity.trapInfoList(groupId, req, builder);
        return builder;
    }


    public static List<Long> getServerIdSet(ActivityInfo activityInfo, int groupId){
        Map<Integer, UnionActivityGroup> groupMap = Cross2UnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
        if(groupMap == null){
            return new ArrayList<>();
        }
        for (Map.Entry<Integer, UnionActivityGroup> groupEntry : groupMap.entrySet()) {
            if(groupEntry.getKey() != groupId){
                continue;
            }
            if(groupEntry.getValue().getServerSet().contains(CrossBaseServer.getInstance().getServerId())){
                return new ArrayList<>(groupEntry.getValue().getServerSet());
            }
        }
        return activityInfo.getServerIdList();
    }

    public static List<Integer> getGroupListByCrossServerId(int activityId){
        Map<Integer, UnionActivityGroup> groupMap = Cross2UnionActivityGroupMgr.getGroupMap(activityId);
        if(groupMap == null){
            return new ArrayList<>();
        }
        List<Integer> groupIdList = new ArrayList<>();
        for (Map.Entry<Integer, UnionActivityGroup> groupEntry : groupMap.entrySet()) {
            if(groupEntry.getValue().getCrossServerId() == CrossBaseServer.getInstance().getServerId()){
                groupIdList.add(groupEntry.getValue().getGroupId());
            }
        }
        return groupIdList;
    }

    //预留修复接口
    public static void repair() {

    }


    /**
     * 秦始皇陵一键跳转至最深层 跨服转发服务
     *
     * @param activityId 活动ID
     * @param userId     玩家ID
     * @return Tomb.TombOneClickJumpResp.Builder
     */
    public static Tomb.TombOneClickJumpResp.Builder oneClickJump(int activityId, long userId) {
        Tomb.TombOneClickJumpResp.Builder builder = Tomb.TombOneClickJumpResp.newBuilder();

        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        int ret = isOpen(activityId, groupId);
        if (ret > 0) { // 再次校验活动是否开启，避免线程运行时活动关闭
            builder.setRet(ret);
            return builder;
        }

        TombActivity activity = activityMap.get(activityId);
        activity.eventOneClickJump(userId, builder);
        builder.setRet(0); // ret为require在此处设置至表示返回成功
        return builder;
    }
}
